extends Node2D
class_name BattleEntity

@onready var animations:AnimatedSprite2D = $Animations
@onready var stateMachine:StateMachine = $StateMachine

signal sigOnMoveArriveTarget

var battleField:BattleField
var data
var moveTargetCell:Vector2
var posBeforeReady:Vector2
var faceBeforeReady

var currentCommandName
var currentCommandData


func init(d):
	data = d
	battleField = get_tree().get_nodes_in_group("BattleField")[0]
	
	animations.sprite_frames = ResourcePreload.resources[data.spriteFrames]
	setPosAndFace()
	stateMachine.addState(Consts.battleEntityStateIdle)
	

func setPosAndFace():
	var cellSize = battleField.cellSize
	animations.animation = "Idle" + data.battleFace
	var targetPos = Vector2(data.battlePos.x * cellSize + cellSize / 2.0, data.battlePos.y * cellSize + cellSize / 2.0)
	position = targetPos
	

func cancelExecuteCommand():
	stateMachine.clearAndAddState(Consts.battleEntityStateCommand)
	battleField.cancelExecuteCommand()
	

func cancelCommand():
	data.battlePos = posBeforeReady
	data.battleFace = faceBeforeReady
	
	position = cell2Pos(data.battlePos)
	stateMachine.clearAndAddState(Consts.battleEntityStateReady2Move)
	

func cell2Pos(cellPos):
	var cellSize = battleField.cellSize
	return  Vector2(cellPos.x * cellSize + cellSize / 2.0, cellPos.y * cellSize + cellSize / 2.0)
	

func _physics_process(delta):
	z_index = position.y
	stateMachine.run(delta)
	
	updateView()
	

func processSelect():
	posBeforeReady = data.battlePos
	faceBeforeReady = data.battleFace
	
	stateMachine.removeState(Consts.battleEntityStateIdle)
	stateMachine.addState(Consts.battleEntityStateReady2Move)
	

func processDeselect():
	stateMachine.removeState(Consts.battleEntityStateReady2Move)
	stateMachine.addState(Consts.battleEntityStateIdle)
	

func processMove(targetCell, callback):
	sigOnMoveArriveTarget.connect(callback)
	moveTargetCell = targetCell
	
	stateMachine.clearAndAddState(Consts.battleEntityStateMove)
	
	
func onMoveArriveTarget():
	sigOnMoveArriveTarget.emit()
	
	
func executeCommand(commandName, data):
	currentCommandName = commandName
	currentCommandData = data
	stateMachine.clearAndAddState(Consts.battleEntityCommandMap[commandName])
	
	
func onHit():
	stateMachine.clearAndAddState(Consts.battleEntityStateHit)
	

func updateView():
	updateViewActionFinish()
	

func updateViewActionFinish():
	var shaderMaterial = animations.material as ShaderMaterial
	shaderMaterial.set_shader_parameter("grayscale", data.battleActionFinish)
	
	
	
